package com.siki.controller.photo;


import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.imageseg.model.v20191230.SegmentBodyRequest;
import com.aliyuncs.imageseg.model.v20191230.SegmentBodyResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.google.gson.Gson;
import com.siki.config.jsonConfig.JsonResult;
import io.swagger.annotations.Api;
import org.json.JSONObject;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Base64;
import java.util.HashMap;

@RequestMapping("/photo")
@Api(tags = "照片处理接口")
@RestController
public class PhotoController {

    private static final String REGION_ID = "cn-shanghai";
    private static final String ACCESS_KEY_ID = "LTAI4G8WzPZiimzx748mohAD";
    private static final String SECRET = "t4MqFpY4rsM92hUkpDICx5221CnhPM";

    @RequestMapping(value = "/get_new_photo",method = RequestMethod.GET)
    public JsonResult get_new_photo(){
        // 初始化一个AipBodyAnalysis
//        AipBodyAnalysis client = new AipBodyAnalysis(APP_ID, API_KEY, SECRET_KEY);

        // 可选：设置网络连接参数
//        client.setConnectionTimeoutInMillis(2000);
//        client.setSocketTimeoutInMillis(60000);

        // 可选：设置代理服务器地址, http和socket二选一，或者均不设置
//        client.setHttpProxy("proxy_host", proxy_port);  // 设置http代理
//        client.setSocketProxy("proxy_host", proxy_port);  // 设置socket代理

//        com.alibaba.fastjson.JSONObject res=sample(client);

//        return GenerateImage(res.get("foreground").toString())==true?JsonResult.success():JsonResult.fail("失败");
        return null;
    }

    public static void main(String[] args) {
        getNewPhoto();
    }
    private static void getNewPhoto(){
        DefaultProfile profile = DefaultProfile.getProfile(REGION_ID,ACCESS_KEY_ID,SECRET);
        IAcsClient client = new DefaultAcsClient(profile);

        SegmentBodyRequest request = new SegmentBodyRequest();
        request.setRegionId("cn-shanghai");
//        request.setAsync(false);
        request.setImageURL("http://sikic.cn/gq_zxxt/img/667b957601b749e591b909d13ceeda6e.jpeg");
        request.setImageURL("http://explorer-image.oss-cn-shanghai.aliyuncs.com/" +
                "1840863369447618/" +
                "test1.png?" +
                "OSSAccessKeyId=LTAI4Fk9FstqSEYnqKJ5Dpeo&" +
                "Expires=1589471949&" +
                "Signature=AVQdULBJvPeftuXGG5UrSsz2OxI%3D");

        request.setImageURL("http://explorer-image.oss-cn-shanghai.aliyuncs.com/" +
                "1840863369447618/test1.png?" +
                "OSSAccessKeyId=LTAI4Fk9FstqSEYnqKJ5Dpeo" +
                "&Expires=1589472199" +
                "&Signature=UJADl5itW9Y8c%2FmehZfI2VoPCbY%3D");


        try {
            SegmentBodyResponse response = client.getAcsResponse(request);
            System.out.println(new Gson().toJson(response));
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            System.out.println("ErrCode:" + e.getErrCode());
            System.out.println("ErrMsg:" + e.getErrMsg());
            System.out.println("RequestId:" + e.getRequestId());
        }
    }





    private static boolean GenerateImage(String imgStr) { //对字节数组字符串进行Base64解码并生成图片
        if (imgStr == null) //图像数据为空
            return false;
        Base64.Decoder decoder = Base64.getDecoder();
        try
        {
            //Base64解码
            byte[] b = decoder.decode(imgStr);
            for(int i=0;i<b.length;++i)
            {
                if(b[i]<0)
                {//调整异常数据
                    b[i]+=256;
                }
            }
            //生成jpeg图片
            String imgFilePath = "/Users/qizai/Desktop/new.jpg";//新生成的图片
            OutputStream out = new FileOutputStream(imgFilePath);
            out.write(b);
            out.flush();
            out.close();
            return true;
        }
        catch (Exception e)
        {
            return false;
        }
    }
}
